package com.yunduansing.core.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yunduansing.core.commons.DbCommon;
import com.yunduansing.core.commons.DbCommon.Grid;
import com.yunduansing.core.dao.GroupDao;
import com.yunduansing.core.dto.GroupDto;
import com.yunduansing.core.model.GroupModel;
import com.yunduansing.core.service.GroupService;
import com.yunduansing.core.utils.ResultUtil;

@Service
public class GroupServiceImpl implements GroupService {
	@Autowired
	private GroupDao dao;

	public GroupModel getByKey(Object key) {
		return dao.getByKey(key);
	}

	public ResultUtil save(GroupModel entity) {
		try{
			if(entity.getId()>0)
				return ResultUtil.init(dao.update(entity)>0);
			else
				return ResultUtil.init(dao.add(entity)>0);
		}catch(Exception e){
			return ResultUtil.init(e);
		}
	}

	@Transactional
	public ResultUtil deleteByKeys(List<Object> keys) {
		try{
			dao.deleteGroupRoleByGroupIds(keys);
			dao.deleteByKeys(keys);
			return ResultUtil.init();
		}catch(Exception e){
			return ResultUtil.init(e);
		}
	}

	public Object pagination(Grid grid, Object search) {
		DbCommon.Pager pager=new DbCommon.Pager();
		pager.setIndex(grid.getIndex());
		pager.setData(dao.pagination(grid, search));
		pager.setRows(dao.pageCount(search));
		return pager;
	}

	@Transactional
	public ResultUtil saveWithRoles(GroupModel group, List<Integer> roleIds) {
		try{
			if(group.getId()>0){
				dao.update(group);
				List<Object> list=new ArrayList<Object>();
				list.add(group.getId());
				dao.deleteGroupRoleByGroupIds(list);
			}else{
				dao.add(group);
			}
			if(roleIds.size()>0)
				dao.saveGroupRole(group.getId(), roleIds);
			return ResultUtil.init();
		}catch(Exception e){
			return ResultUtil.init(e);
		}
	}

	public GroupDto getGroupWithRolesById(int id) {
		return dao.getGroupWithRolesById(id);
	}

	public List<GroupModel> getAll() {
		return dao.getAll();
	}

}
